package vn.csp.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * 
 * @author Tống Bảo Lộc (loctong@gmail.com)
 *
 */
public class JSONParser {
	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";
	public JSONParser() {

	}
	/**
	 * @author Tống Bảo Lộc (loctong@gmail.com)
	 * @param param
	 * @return
	 */
	public JSONObject getJSONObject(String url,String[] ...param) { 
		//params
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		for (int i = 0; i < param.length; i++) {
			nameValuePairs.add(new BasicNameValuePair(param[i][0],param[i][1]));
		}
		try {
			// Server request
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			//Server response
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return chuyenChuoiThanhJson();
	}
	/**
	 * @author Tống Bảo Lộc (loctong@gmail.com)
	 * @return
	 */
	public JSONObject chuyenChuoiThanhJson(){
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(	
					is, "UTF-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			//			is.close(); // oop ?????????????????????????????????????
			json = sb.toString();
			Log.i(json,json);
		} catch (Exception e) {
			Log.e("Lỗi lúc chuyển sang -> JSON", e.toString());
		}
		// Chuyển thành JSON object
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("Lỗi lúc chuyển sang -> JSON", e.toString());
		}
		return jObj;
	}
}